package com.kbbywyclient.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.kbbywyclient.R;
import com.kbbywyclient.data.entity.SalesSetting;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.di.module.NewMainModule;
import com.kbbywyclient.presenter.NewMainPresenter;
import com.kbbywyclient.ui.activity.base.BaseActivity;
import com.kbbywyclient.ui.contarct.NewMainContract;
import com.kbbywyclient.ui.fragment.base.BaseFragment;
import com.kbbywyclient.ui.fragment.tab.IndexFragment;
import com.kbbywyclient.ui.fragment.tab.MineFragment;
import com.kbbywyclient.ui.helper.ShareHelper;
import com.kbbywyclient.ui.pop.SharePopWin;
import com.kbbywyclient.util.ToastUtil;
import com.kbbywyclient.util.ViewUtils;
import com.kbbywyclient.util.download.TDevice;
import com.kbbywyclient.util.pre.PreUtils;
import com.kbbywyclient.widget.CustomPopwin;
import com.umeng.message.common.UmLog;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;

/**
 * 首页
 */
public class MainActivity extends BaseActivity implements NewMainContract.View {
    public static final int INDEX_INDEX = 0;
    public static final int INDEX_MINE = 1;

    public static final String SET_INDEX_FRAGMENT_B = "setIndexFragment";//是否设置当前选中fragment为首页

    private static int textColorSelected = 0xFF2BBBB1;//tab项选中文字颜色
    private static int textColorNormal = 0xFFBBBBBB;//tab项未选中文字颜色

    @BindViews({R.id.tv_nav_index, R.id.tv_nav_mine})
    List<TextView> textViews;
    private int[] arraySelectedDrawable = new int[]{R.mipmap.icon_index_selected,
            R.mipmap.icon_mine_selected};//tab项选中图标

    private int[] arrayNormalDrawable = new int[]{R.mipmap.icon_index_normal,
            R.mipmap.icon_mine_normal};//tab项未选中图标

    private BaseFragment[] fragments=new BaseFragment[2];

    private int showFragIndex = 0;//需要展示的fragment下标位置

    private long mExitTime;
    private AMapLocationClient mLocationClient = null;

    private int curVersion = -1;

    private CustomPopwin popwin;
    private boolean isDownLoad = false;

    @BindView(R.id.ll_all)
    LinearLayout ll_all;

    @Inject
    NewMainPresenter newMainPresenter;

    ShareHelper shareHelper;

    @Override
    public int provideContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isDownLoad) {
            if (PreUtils.isLogin(this)) {
                newMainPresenter.getSalesSetting(PreUtils.getUser(this).getSalesID() + "");
            }
        }
    }

    @Override
    protected void initView() {
        //高德定位
        initLocation();
        setCurrentFragment(INDEX_INDEX);
    }

    @Override
    public void initData() {

    }

    @OnClick({R.id.tv_nav_index, R.id.tv_nav_mine})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_nav_index:
                setCurrentFragment(INDEX_INDEX);
                break;
            case R.id.tv_nav_mine:
                setCurrentFragment(INDEX_MINE);
                break;
        }
    }

    @Override
    public void initAppComponent(AppComponent appComponent) {
        appComponent.getNewMainComponent(new NewMainModule(this)).inject(this);
    }

    private void initLocation() {
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();

        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果
        mLocationOption.setOnceLocation(true);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);

        //声明定位回调监听器
        AMapLocationListener mLocationListener = aMapLocation -> {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    //解析定位结果
                    UmLog.i("aaa", "city: " + aMapLocation.getCity());
                    PreUtils.setCityName(this, aMapLocation.getCity());
                    String city = PreUtils.getUser(this).getCityName();
                    UmLog.i("aaa", "city1: " + city);
                    mLocationClient.stopLocation();
                }
            }
        };

        //初始化定位
        mLocationClient = new AMapLocationClient(this);
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();

    }

    /**
     * 设置当前显示的fragment
     *
     * @param fragmentIndex 需要显示的fragment下标
     */
    public void setCurrentFragment(int fragmentIndex) {
        if (fragmentIndex >= 0 && fragmentIndex < textViews.size()) {
            FragmentManager manager = getSupportFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            switch (fragmentIndex) {
                case INDEX_INDEX:
                    if (manager.findFragmentByTag(String.valueOf(INDEX_INDEX)) == null) {
                        if(fragments[INDEX_INDEX]==null){
                            fragments[INDEX_INDEX]=new IndexFragment();
                        }
                    }else{
                        if(fragments[INDEX_INDEX]==null){
                            fragments[INDEX_INDEX]=
                                    (BaseFragment) manager.findFragmentByTag(String.valueOf(INDEX_INDEX));
                        }
                    }
                    if(!fragments[INDEX_INDEX].isAdded()){
                        transaction.add(R.id.fragment_container,
                                fragments[INDEX_INDEX],String.valueOf(INDEX_INDEX));
                    }
                    showFragIndex = INDEX_INDEX;
                    break;
                case INDEX_MINE:
                    if (manager.findFragmentByTag(String.valueOf(INDEX_MINE)) == null) {
                        if(fragments[INDEX_MINE]==null){
                            fragments[INDEX_MINE]=new MineFragment();
                        }
                    }else {
                        if(fragments[INDEX_MINE]==null){
                            fragments[INDEX_MINE]=
                                    (BaseFragment) manager.findFragmentByTag(String.valueOf(INDEX_MINE));
                        }
                    }
                    if(!fragments[INDEX_MINE].isAdded()){
                        transaction.add(R.id.fragment_container,
                                fragments[INDEX_MINE], String.valueOf(INDEX_MINE));
                    }
                    showFragIndex = INDEX_MINE;
                    break;
            }
                TextView tv;
                BaseFragment fragment;
                for (int i = 0; i < fragments.length; i++) {
                    fragment=fragments[i];
                    if (i == showFragIndex) {
                        tv = textViews.get(i);
                        tv.setTextColor(textColorSelected);
                        tv.setCompoundDrawablesWithIntrinsicBounds(null,
                                ContextCompat.getDrawable(getApplicationContext(), arraySelectedDrawable[i]), null, null);
                        if(fragment!=null){
                            transaction.show(fragment);
                        }
                    } else {
                        tv = textViews.get(i);
                        tv.setTextColor(textColorNormal);
                        tv.setCompoundDrawablesWithIntrinsicBounds(null,
                                ContextCompat.getDrawable(getApplicationContext(), arrayNormalDrawable[i]), null, null);
                        if(fragment!=null){
                            transaction.hide(fragment);
                        }
                    }
                }
                if(showFragIndex==INDEX_INDEX){
                    setScreenName("首页");
                }else{
                    setScreenName("我的");
                }
                transaction.commit();
        }
    }

    /**
     * 更改返回按键的响应事件
     *
     * @param keyCode
     * @param event
     * @return
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                ToastUtil.showShort(getString(R.string.exit_application));
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
                if (mLocationClient != null) {
                    mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
                    mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
                }
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void showLoadingDialog(String s) {
        showProgress(s);
    }

    @Override
    public void closeLoadingDialog() {
        dismissProgress();
    }

    @Override
    public void loadSucSaleSetting(SalesSetting salesSetting) {
        curVersion = salesSetting.getSalesSetting().getAndroidVersion();
        PreUtils.setVersionCode(MainActivity.this,curVersion);
        if (TDevice.getVersionCode() < curVersion) {//新版本
            showDialogView(salesSetting.getSalesSetting().getAndroidDownloadURL());
        }
    }

    @Override
    public void loadFaiSaleSetting(String errorMsg) {

    }

    private void showDialogView(String url) {
        View proView = LayoutInflater.from(this).inflate(R.layout.pop_custom_download, null, false);

        TextView tv_title = (TextView) proView.findViewById(R.id.tv_title);
        TextView tv_content = (TextView) proView.findViewById(R.id.tv_content);
        Button btn_determine = (Button) proView.findViewById(R.id.btn_determine);

        ViewUtils.setText(tv_title, "提示");
        ViewUtils.setText(tv_content, "卡贝贝新版本发布了,来更新一波吧！");

        if (popwin == null) {
            popwin = new CustomPopwin(this, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f, false);
        }
        popwin.setContentView(proView);
        popwin.setOutsideTouchable(false);
        popwin.setOnDismissListener(() -> {
            if(!isDownLoad){
                finish();
            }
        });
        popwin.showAtLocation(ll_all, Gravity.NO_GRAVITY, 0, 0);

        btn_determine.setOnClickListener(v -> {
            TDevice.openDownLoadService(this, url, "更新中...");
            isDownLoad = true;
            popwin.dismiss();
        });
    }


    public void share(ShareHelper.ShareBody shareBody) {
        new SharePopWin(this, platForm -> {
            shareBody.platForm = platForm;
            if (shareHelper == null) {
                shareHelper = new ShareHelper(MainActivity.this,"首页-热门推荐-列表项分享");
            }
            shareHelper.share(shareBody);
        }).showAtLocation(ll_all, Gravity.NO_GRAVITY, 0, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (shareHelper != null) {
            shareHelper.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getBooleanExtra(SET_INDEX_FRAGMENT_B, false)) {
            setCurrentFragment(INDEX_INDEX);
            intent.putExtra(SET_INDEX_FRAGMENT_B, false);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("showFragIndex", showFragIndex);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            showFragIndex = savedInstanceState.getInt("showFragIndex");
            setCurrentFragment(showFragIndex);
        }
    }
}
